package com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.hyphenate.EMClientListener;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMContactListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMMultiDeviceListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.fragment.huanxinUi.EaseConversationListFragment;
import com.hyphenate.easeui.utils.Preferences;
import com.hyphenate.easeui.utils.map.JSONUtils;
import com.hyphenate.util.NetUtils;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.Parameter;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.MessageDialog;
import com.kongzue.kongzueupdatesdk.UpdateInfo;
import com.kongzue.kongzueupdatesdk.UpdateUtil;
import com.kongzue.takephoto.TakePhotoUtil;
import com.ninetaildemonfox.zdl.socialproject.base.BaseActivity;
import com.ninetaildemonfox.zdl.ninetaildemonfox.utils.AppManager;
import com.ninetaildemonfox.zdl.socialproject.BuildConfig;
import com.ninetaildemonfox.zdl.socialproject.R;
import com.ninetaildemonfox.zdl.socialproject.SpApplication;
import com.ninetaildemonfox.zdl.socialproject.huanxin.DemoHelper;
import com.ninetaildemonfox.zdl.socialproject.jpush.ExampleUtil;
import com.ninetaildemonfox.zdl.socialproject.mvp.presenter.DrawAmountPresenter;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.adapter.MainFragmentPageAdapter;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.main.DatingHallFragment;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.main.MyFragment;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.main.NewsFragment;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.main.RadioStationFragment;
import com.ninetaildemonfox.zdl.socialproject.utils.NoScrollViewPager;
import com.ninetaildemonfox.zdl.socialproject.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * @author NineTailDemonFox
 * @date 2019/7/15 9:51
 * 功能描述： 主界面
 * 联系方式：1037438704@qq.com
 */
public class MainActivity extends BaseActivity {
    private static final String TAG = "MainActiviy";
    private DrawAmountPresenter presenter;
    private NoScrollViewPager mainViewPager;
    private RadioGroup mainRgp;
    private List<Fragment> fragemnts;
    private long exitTime = 0;
    private String tuisong;
    private EaseConversationListFragment conversationListFragment;
    public static int thisMainCount = 0;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_main;
    }

    @Override
    protected void onInitialization(Bundle bundle) {
        tuisong = Preferences.getInstance().getString(this, "user", "tuisong");
        conversationListFragment = new EaseConversationListFragment();
        update();
        onListen(1);
        initView();
        initData();
        setAdapter();
        setListener();
        location();
    }

    private void location() {
        HttpRequest.POST(getApplicationContext(), "Index/setLonLat"
                , new Parameter()
                        .add("token", Preferences.getInstance().getString(getApplicationContext(), "user", "token"))
                        .add("lon", SpApplication.LONGITUDE)
                        .add("lat", SpApplication.LATITUDE)
                , new ResponseListener() {
                    @Override
                    public void onResponse(String response, Exception error) {
                    }
                });
    }

    private void setListener() {
        //viewPager的滑动监听
        mainViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                //获取当前位置的RadioButton
                RadioButton rb = (RadioButton) mainRgp.getChildAt(position);
                //设置为true
                rb.setChecked(true);
            }
        });
        //RadioGroup的事件监听
        mainRgp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                for (int index = 0; index < mainRgp.getChildCount(); index++) {
                    RadioButton rb = (RadioButton) mainRgp.getChildAt(index);
                    if (rb.isChecked()) {
                        mainViewPager.setCurrentItem(index, false);
                        break;
                    }
                }
            }
        });
    }

    private void setAdapter() {
        //实例化适配器
        MainFragmentPageAdapter adapter = new MainFragmentPageAdapter(getSupportFragmentManager(), fragemnts);
        mainViewPager.setOffscreenPageLimit(fragemnts.size());
        //设置适配器
        mainViewPager.setAdapter(adapter);
    }

    private RadioStationFragment radioStationFragment;

    private void initData() {
        radioStationFragment = RadioStationFragment.newInstance();
        fragemnts = new ArrayList<>();
        fragemnts.add(DatingHallFragment.newInstance());
        fragemnts.add(radioStationFragment);
        fragemnts.add(NewsFragment.newInstance());
        fragemnts.add(MyFragment.newInstance());
    }

    private void initView() {
        setAlias();
        registerBroadcastReceiver();
        //注册一个监听连接状态的listener
        EMClient.getInstance().addConnectionListener(new MyConnectionListener());
        EMClient.getInstance().contactManager().setContactListener(new MyContactListener());
        EMClient.getInstance().addClientListener(clientListener);
        EMClient.getInstance().addMultiDeviceListener(new MyMultiDeviceListener());


        presenter = new DrawAmountPresenter(this);
        presenter.isLing(token);
        mainViewPager = (NoScrollViewPager) findViewById(R.id.main_viewpager);
        mainRgp = (RadioGroup) findViewById(R.id.main_rgp);
        //设置默认第一个为选中状态
        RadioButton rb = (RadioButton) mainRgp.getChildAt(0);
        rb.setChecked(true);
        TakePhotoUtil.getInstance(this).setReturnPhoto(new TakePhotoUtil.ReturnPhoto() {
            @Override
            public void onGetPhotos(String[] selectImagePaths) {

                if (thisMainCount == 0) {

                } else if (thisMainCount == 4) {

                } else {
                    //这里获取文件路径并上传
                    String selectImagePath = selectImagePaths[0];
                    //                             文件路径             1上传    2设置	              1视频                    2 图片
                    PictureUploadActivity.start(me, selectImagePath, "1", "2");
                }
            }

            @Override
            public void onError(Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 按两次退出应用
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                return super.onKeyDown(keyCode, event);
            }
        }
        return true;
    }

    /**
     * 自定义toast
     */
//    private void showTips(int iconResId, String tips) {
//        if (tipsToast != null) {
//            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
//                tipsToast.cancel();
//            }
//        } else {
//            tipsToast = TipsToast.makeText(MainActivity.this.getApplication()
//                    .getBaseContext(), tips, TipsToast.LENGTH_SHORT);
//        }
//        tipsToast.show();
//        tipsToast.setIcon(iconResId);
//        tipsToast.setText(tips);
//    }


    //======================环信======================
    //实现ConnectionListener接口
    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
        }

        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (error == EMError.USER_REMOVED) {
                        ToastUtil.show("帐号已经被移除");
                        // 显示帐号已经被移除
                    } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        // 显示帐号在其他设备登录
//                        ToastUtil.show("帐号在其他设备登录");
                    } else {
                        if (NetUtils.hasNetwork(me)) {
//                            ToastUtil.show("您的网速");
                        } else {
                            ToastUtil.show("当前网络不可用，请检查网络设置");
                        }
                    }
                }
            });
        }
    }

    //    9728
    EMMessageListener messageListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            for (EMMessage message : messages) {
                DemoHelper.getInstance().getNotifier().vibrateAndPlayTone(message);
            }
            refreshUIWithMessage();

        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            refreshUIWithMessage();
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
        }

        @Override
        public void onMessageRecalled(List<EMMessage> list) {
            refreshUIWithMessage();
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }
    };
    EMClientListener clientListener = new EMClientListener() {
        @Override
        public void onMigrate2x(boolean success) {
            Toast.makeText(MainActivity.this, "onUpgradeFrom 2.x to 3.x " + (success ? "success" : "fail"), Toast.LENGTH_LONG).show();
            if (success) {
                refreshUIWithMessage();
            }
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
//        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
//        EMClient.getInstance().removeClientListener(clientListener);
        DemoHelper sdkHelper = DemoHelper.getInstance();
        sdkHelper.popActivity(this);
    }

    @Override
    protected void onDestroy() {
        onListen(0);
        super.onDestroy();
        unregisterBroadcastReceiver();
    }

    private void onListen(int count) {
        HttpRequest.POST(me, "Index/listen"
                , new Parameter()
                        .add("token", token)
                        .add("type", count)
                , new ResponseListener() {
                    @Override
                    public void onResponse(String response, Exception error) {
                    }
                });
    }


    private void unregisterBroadcastReceiver() {
        broadcastManager.unregisterReceiver(broadcastReceiver);
    }


    private void refreshUIWithMessage() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // refresh unread count
                updateUnreadLabel();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        DemoHelper sdkHelper = DemoHelper.getInstance();
        sdkHelper.pushActivity(this);
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
    }

    public class MyContactListener implements EMContactListener {
        @Override
        public void onContactAdded(String username) {
        }

        @Override
        public void onContactDeleted(final String username) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (ChatActivity.activityInstance != null && ChatActivity.activityInstance.toChatUsername != null &&
                            username.equals(ChatActivity.activityInstance.toChatUsername)) {
                        String st10 = getResources().getString(R.string.have_you_removed);
                        Toast.makeText(me, ChatActivity.activityInstance.getToChatUsername() + st10, Toast.LENGTH_LONG)
                                .show();
                        ChatActivity.activityInstance.finish();
                    }
                }
            });
        }

        @Override
        public void onContactInvited(String username, String reason) {
        }

        @Override
        public void onFriendRequestAccepted(String username) {
        }

        @Override
        public void onFriendRequestDeclined(String username) {
        }
    }

    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver broadcastReceiver;

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("action_contact_changed");
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                updateUnreadLabel();
            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    /**
     * update unread message count
     */
    public void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
        if (count > 0) {
            if (tuisong.equals("1")) {
                initSendNotific();
            }
        }
    }

    protected void initSendNotific() {
        NotificationManager notificationManager = (NotificationManager) me.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = null;
        NotificationCompat.Builder builder = new NotificationCompat.Builder(me);
        String title = "您有一条新的消息";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_MAX;
            String channelId = "chat";//消息通道的id，以后可以通过该id找到该消息通道
            String channelName = "聊天消息";//消息通道的name
            @SuppressLint("WrongConstant") NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
            notificationManager.createNotificationChannel(channel);
            Intent mIntent = new Intent(me, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(me, 0, mIntent, 0);
            notification = new Notification.Builder(me)
                    .setChannelId("chat")
                    .setContentTitle(title)
                    .setContentText("请查阅")
                    .setSmallIcon(R.mipmap.ic_logo)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .build();
            notificationManager.notify(2, notification);
        } else {
            builder.setAutoCancel(true)
                    .setContentText(title)
                    .setContentTitle("")
                    .setSmallIcon(R.mipmap.ic_logo);
            Intent mIntent = new Intent(me, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(me, 0, mIntent, 0);
            builder.setContentIntent(pendingIntent);
            notificationManager.notify(2, builder.build());
        }
    }


    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        int chatroomUnreadMsgCount = 0;
        unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMessageCount();
        for (EMConversation conversation : EMClient.getInstance().chatManager().getAllConversations().values()) {
            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom) {
                chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
            }
        }
        return unreadMsgCountTotal - chatroomUnreadMsgCount;
    }


    public class MyMultiDeviceListener implements EMMultiDeviceListener {

        @Override
        public void onContactEvent(int event, String target, String ext) {

        }

        @Override
        public void onGroupEvent(int event, String target, final List<String> username) {
            switch (event) {
                case EMMultiDeviceListener.GROUP_LEAVE:
                    ChatActivity.activityInstance.finish();
                    break;
                default:
                    break;
            }
        }
    }

    //======================环信======================
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        TakePhotoUtil.getInstance(me).onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10000 && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            int poation = bundle.getInt("poation");
            radioStationFragment.itemCount(poation);
//            ToastUtil.show("拿到的数据" + bundle.getInt("poation"));
        }
    }


    //============================================== 极光推送==========================
    // 这是来自 JPush Example 的设置别名的 Activity 里的代码。一般 App 的设置的调用入口，在任何方便的地方调用都可以。
    private void setAlias() {
        String alias = token;
        if (TextUtils.isEmpty(alias)) {
//            ToastUtil.show("极光推送别名错误");
            return;
        }
        if (!ExampleUtil.isValidTagAndAlias(alias)) {
//            ToastUtil.show("极光推送别名错误");
            return;
        }

        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }
            ExampleUtil.showToast(logs, getApplicationContext());
        }
    };
    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d(TAG, "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };

    //============================================== 极光推送==========================
    private void update() {
        HttpRequest.POST(me, "Upgrade/upgrade"
                , new Parameter()
                , new ResponseListener() {
                    @Override
                    public void onResponse(String response, Exception error) {
                        if (error == null) {
                            Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                            if (map.get("code").equals("1")) {
                                Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                                int code = BuildConfig.VERSION_CODE;
                                String versionCode = data.get("versionCode");
                                if (versionCode != null) {
                                    Integer integer = Integer.valueOf(versionCode);
                                    if (code < integer) {
                                        update(data.get("versionName"), data.get("url"), "");
                                    }
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 软件更新
     */
    private void update(String vernum, String url, String cString) {
        //立即开通
        MessageDialog.show(me, "检测到新版本", "请更新" + vernum, "确认")
                .setOnOkButtonClickListener(new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        UpdateInfo updateInfo = new UpdateInfo()
                                .setDownloadUrl(url);
                        UpdateUtil updateUtil = new UpdateUtil(me, BuildConfig.APPLICATION_ID)
                                .setOnDownloadListener(new UpdateUtil.OnDownloadListener() {
                                    @Override
                                    public void onStart(long downloadId) {
                                        Log.i("MainActivity", "onStart: 下载开始");
                                        ToastUtil.show("开始下载");
                                    }

                                    @Override
                                    public void onDownloading(long downloadId, int progress) {
                                        Log.i("MainActivity", "onStart: 下载中：" + progress);
                                    }

                                    @Override
                                    public void onSuccess(long downloadId) {
                                        Log.i("MainActivity", "onStart: 下载完成");
                                        ToastUtil.show("下载完成");
                                    }

                                    @Override
                                    public void onCancel(long downloadId) {

                                    }
                                });
                        updateUtil.doUpdate(updateInfo);
                        return false;
                    }
                }).setCancelable(false).show();
    }
}